package com.zhongjian.technologycal.mall.activity.main.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.main.bean.PaymentInfoBean;
import com.zhongjian.technologycal.mall.activity.personal.activity.SettingPayPasswordActivity;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.UserInfoBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.AppTools;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.view.EaseSwitchButton;
import com.zhongjian.technologycal.mall.view.PasswordInputView;

import butterknife.BindView;
import butterknife.OnClick;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2018/4/12.
 * 提交报名信息页面的处理
 */

public class MineEnrollActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.enroll_iv_course_icon)
    ImageView enroll_iv_course_icon;
    @BindView(R.id.enroll_tv_course_title)
    TextView enroll_tv_course_title;
    @BindView(R.id.enroll_tv_course_time)
    TextView enroll_tv_course_time;
    @BindView(R.id.enroll_tv_course_address)
    TextView enroll_tv_course_address;
    @BindView(R.id.enroll_tv_course_money)
    TextView enroll_tv_course_money;
    @BindView(R.id.enroll_course_switch_owner_leavel)
    EaseSwitchButton enroll_course_switch_owner_leavel;
    @BindView(R.id.enroll_tv_course_total_price)
    TextView enroll_tv_course_total_price;
    private MaterialDialog materialDialog = null;
    private int type = 0;
    private String titleName;
    private double meetingPrice;
    private String startTime;
    private String meetingAddress;
    private String meetingPhoto;
    private double realPrice;
    private double remainElecNum = 0;
    private double realElecNum0 = 0;
    private double realElecNum1 = 0;
    private double realElecNum = 0;
    private int courseId;
    private Dialog payDialog = null;
    private String orderNo;
    private String userName;

    @Override
    protected void beforeInit() {
        super.beforeInit();
        titleName = getIntent().getStringExtra("titleName");
        meetingPrice = getIntent().getDoubleExtra("meetingPrice", 0);
        startTime = getIntent().getStringExtra("startTime");
        meetingAddress = getIntent().getStringExtra("meetingAddress");
        meetingPhoto = getIntent().getStringExtra("meetingPhoto");
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initViewPersonInfo();
        tv_main_title.setText("提交报名");

        enroll_tv_course_title.setText(titleName);
        realPrice = meetingPrice;
        enroll_tv_course_total_price.setText("¥ " + realPrice);
        enroll_tv_course_time.setText("开课时间：" + startTime);
        enroll_tv_course_address.setText("开课地点：" + meetingAddress);
        courseId = getIntent().getIntExtra("tabStutusId", 0);
        if (!TextUtils.isEmpty(meetingPhoto)) {
            Picasso.get().load(BaseContacts.BASE_URL + meetingPhoto).into(enroll_iv_course_icon);
        }
        enroll_course_switch_owner_leavel.closeSwitch();

        enroll_course_switch_owner_leavel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (enroll_course_switch_owner_leavel.isSwitchOpen()) {
                    enroll_course_switch_owner_leavel.closeSwitch();
                    computeCount();

                } else {
                    enroll_course_switch_owner_leavel.openSwitch();
                    computeCount();
                }
            }
        });

    }

    @Override
    public void initPresenter() {

    }


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_commit_enroll;
    }

    /**
     * 计算抵扣 /// * 100 作为精度计算
     */
    private void computeCount() {
        double realPrice0 = meetingPrice;
        double realPrice3 = 0;
        double realElecNum3 = 0;
        double realElecNum4 = 0;
        if (enroll_course_switch_owner_leavel.isSwitchOpen()) {
            if (remainElecNum >= realPrice0) {
                realPrice3 = 0;
                realElecNum3 = realPrice0;
                realElecNum4 = AppTools.sub(remainElecNum,realPrice0);
            } else {
                realPrice3 = AppTools.sub(realPrice0,remainElecNum);
                realElecNum4 = 0;
                realElecNum3 = remainElecNum;
            }
            realElecNum = realElecNum3;
            realPrice = realPrice3;
            realElecNum1 = realElecNum4;
        } else if(enroll_course_switch_owner_leavel.isSwitchClose()){
            realPrice = realPrice0;
            realElecNum0 = remainElecNum;
            realElecNum3 = 0;
            realElecNum1 = remainElecNum;
        }
        realElecNum = realElecNum3;
        enroll_tv_course_total_price.setText("¥ " + realPrice);
        enroll_tv_course_money.setText("可用现金币 " + realElecNum1);
    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    /**
     * 获取钱包数据
     */
    private void initViewPersonInfo() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).getUrlRequestAccountBalance(UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            UserInfoBean userInfoBean = gson.fromJson(responseBody.string(), UserInfoBean.class);
                            if (userInfoBean.getError_code() == 0) {
                                remainElecNum = userInfoBean.getData().getPersonDataMap().getRemainElecNum();
                                realElecNum1 = remainElecNum;
                                userName = userInfoBean.getData().getPersonDataMap().getUserName();
                                enroll_tv_course_money.setText("可用现金币 " + realElecNum1);
                            } else if (userInfoBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else {
                                ToastUitl.showShort(userInfoBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    /**
     * 课程报名
     */
    private void initViewPayMentCommit() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestSignupforcourse(UserUtils.getUserToken(),
                courseId, realElecNum, realPrice,
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(MineEnrollActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();

                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            PaymentInfoBean paymentInfoBean = gson.fromJson(responseBody.string(), PaymentInfoBean.class);
                            if (paymentInfoBean.getError_code() == 0) {
                                orderNo = paymentInfoBean.getData().getInfo();
                                if (paymentInfoBean.getData().getType().equals("1")) {//同步支付
                                    type = 1;
                                    initViewShowDialog();

                                } else if (paymentInfoBean.getData().getType().equals("2")) {//支付宝支付
                                    type = 2;
                                    Intent intent = new Intent();
                                    intent.setClass(getBaseContext(), PayMentCourseActivity.class);
                                    intent.putExtra("singData", paymentInfoBean.getData().getInfo());
                                    startActivity(intent);
                                    finish();

                                } else if (paymentInfoBean.getData().getType().equals("3")) {//混合支付
                                    type = 3;
                                    initViewShowDialog();
                                }

                            } else if (paymentInfoBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else {
                                ToastUitl.showShort(paymentInfoBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    /**
     * 商学院课程同步支付
     */
    private void initViewSynchandleordercc(String orderNo) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestSynchandleordercc(UserUtils.getUserToken(),
                orderNo,
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(MineEnrollActivity.this);

                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                ToastUitl.showShort(baseBean.getError_message());
                                finish();
                            } else {
                                ToastUitl.showShort(baseBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    /**
     * 验证支付密码
     *
     * @param password
     */

    private void initRequestPayPassword(String password) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestPayPassword(UserUtils.getUserToken(),
                        password, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(MineEnrollActivity.this);
                            }

                            @Override
                            public void onCompleted() {
                                LoadingDialog.cancelDialogForLoading();

                            }

                            @Override
                            public void onError(Throwable e) {
                                LoadingDialog.cancelDialogForLoading();
                                ToastUitl.showShort(e.getMessage());
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        if (type == 3) {
                                            Intent intent = new Intent();
                                            intent.setClass(getBaseContext(), PayMentCourseActivity.class);
                                            intent.putExtra("singData", orderNo);
                                            startActivity(intent);
                                            finish();
                                        } else {
                                            ToastUitl.showShort(baseBean.getError_message());
                                            initViewSynchandleordercc(orderNo);
                                        }
                                        payDialog.dismiss();
                                    } else if (baseBean.getError_code() == -1) {
                                        Intent intent = new Intent();
                                        intent.setClass(getBaseContext(), SettingPayPasswordActivity.class);
                                        intent.putExtra("username", userName);
                                        startActivity(intent);
                                        ToastUitl.showShort(baseBean.getError_message());
                                        payDialog.dismiss();

                                        /**
                                         * 冻结
                                         */
                                    } else if (baseBean.getError_code() == 5) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                        payDialog.dismiss();
                                        /**
                                         * 密码错误
                                         */
                                    } else if (baseBean.getError_code() == 1) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    } else if (baseBean.getError_code() == 3) {



                                    } else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });

    }

    private void initViewShowDialog() {
        payDialog = new Dialog(MineEnrollActivity.this, R.style.dialog_style1);
        LinearLayout layout;
        LayoutInflater inflater = (LayoutInflater) MineEnrollActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout = (LinearLayout) inflater.inflate(R.layout.dialog_hint,
                null);
        final PasswordInputView tv_hint = (PasswordInputView) layout
                .findViewById(R.id.again_paypswd_pet);
        layout.findViewById(R.id.dialog_btn_cancel).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        payDialog.dismiss();
                    }
                });
        layout.findViewById(R.id.dialog_btn_ensure).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (TextUtils.isEmpty(tv_hint.getText().toString().trim())) {
                            ToastUitl.showShort("支付密码不能为空");
                            return;
                        } else if (tv_hint.getText().toString().trim().length() < 6) {
                            ToastUitl.showShort("请输入6位的支付密码");
                            return;
                        }
                        initRequestPayPassword(tv_hint.getText().toString().trim());

                    }
                });
        payDialog.setContentView(layout);
        payDialog.show();
    }

    /**
     * 提交报名支付
     */
    @OnClick(R.id.enroll_tv_course_commit)
    public void onClickPaymentCommit() {
        materialDialog = new MaterialDialog(MineEnrollActivity.this)
                .setMessage("确定提交报名吗？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initViewPayMentCommit();
                        materialDialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        materialDialog.dismiss();
                    }
                });
        materialDialog.setCanceledOnTouchOutside(true);
        materialDialog.show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        type = 0;
    }
}
